import 'dart:async';

import 'package:async_test/common/test_page.dart';

class StreamZipZoneTestPage extends TestPage {
  StreamZipZoneTestPage(super.title){
    StreamController controller;
    controller = StreamController();
    testStream('单次异步', controller, controller.stream);
    controller = StreamController.broadcast();
    testStream('广播异步', controller, controller.stream);
    controller = StreamController();
    testStream('作为广播异步', controller, controller.stream.asBroadcastStream());

    controller = StreamController(sync: true);
    testStream('单次同步', controller, controller.stream);
    controller = StreamController.broadcast(sync: true);
    testStream('广播同步', controller, controller.stream);
    controller = StreamController(sync: true);
    testStream('作为广播同步', controller, controller.stream.asBroadcastStream());
  }

  void testStream(String name, StreamController controller, Stream stream) {
    test(name, () {
      var outer = Zone.current;
      runZoned(() {
        var newZone1 = Zone.current;
        late StreamSubscription sub;
        sub = stream.listen((v) {
          expect(v);
          expect(Zone.current);
          outer.run(() {
            sub.onData((v) {
              expect(v);
              expect(Zone.current);
              runZoned(() {
                sub.onData((v) {
                  expect(v);
                  expect(Zone.current);
                });
              });
              if (controller is SynchronousStreamController) {
                scheduleMicrotask(() => controller.add(87));
              } else {
                controller.add(87);
              }
            });
          });
          if (controller is SynchronousStreamController) {
            scheduleMicrotask(() => controller.add(37));
          } else {
            controller.add(37);
          }
        });
      });
      controller.add(42);
    });
  }
}